<template>
  <div class="user_information">
    <van-cell-group>
      <van-cell v-if="code" title="推荐人" :value="upname + ' ' + upxiaoqu" />
      <van-field v-model="realname" label="姓名" placeholder="请输入您的姓名" input-align="right" :error="!!$vuelidation.error('realname')">
        <span slot="icon" class="red flex">*<van-icon name="edit" /></span>
      </van-field>
      <van-field v-model="mobile" label="手机号码" placeholder="请输入您的手机号码" input-align="right" :error="!!$vuelidation.error('mobile')">
        <span slot="icon" class="red flex">*<van-icon name="edit" /></span>
      </van-field>
      <van-field v-model="lasttel" label="紧急联系人" placeholder="请输入您的预备收货人电话" input-align="right" :error="!!$vuelidation.error('lasttel')">
        <span slot="icon" class="red flex">*<van-icon name="edit" /></span>
      </van-field>
      <van-field v-model="idCard" label="身份证号" placeholder="请输入您的身份证号" input-align="right" :error="!!$vuelidation.error('idCard')">
        <span slot="icon" class="red flex">*<van-icon name="edit" /></span>
      </van-field>
    </van-cell-group>

    <van-cell-group>
      <van-cell v-if="centers.length > 0" title="所属服务中心" :value="centerText" @click="showCenter = true" isLink>
        <span slot="right-icon" style="color: red;">*<van-icon name="arrow" color="gray" /></span>
      </van-cell>
      <van-cell title="所在地区" :value="area" @click="showArea = true" isLink>
         <span slot="right-icon" style="color: red;">*<van-icon name="arrow" color="gray" /></span>
     </van-cell>
      <van-field
        v-model="tXiaoqu"
        label="小区名称"
        placeholder="小区名称+期次/苑/区（限26个中文）"
        input-align="right"
        :error="!!$vuelidation.error('tXiaoqu')"
        @click-icon="searchLocation"
        @keydown="onXiaoquInput"
        ref="xiaoquInput">
        <span slot="icon" class="red flex">*<van-icon name="edit" /></span>
      </van-field>
      <van-field v-model="tShopname" label="详细地址" placeholder="栋号+门牌号+店名（限32个中文）" input-align="right" :error="!!$vuelidation.error('tShopname')">
        <span slot="icon" class="red flex">*<van-icon name="edit" /></span>
      </van-field>
    </van-cell-group>
    <van-cell-group>
      <van-cell v-for="(image, i) in images" :key="i" :title="image.title" class="cell_middle">
        <van-uploader :afterRead="afterRead(i)">
          <img :src="image.file.content" width="100%" v-if="image.file">
          <div v-else class="flex">
            <span class="image_text">请上传清晰照片，文字内容清楚</span>
            <div class="user_image_upload">
              <van-icon name="camera_full"></van-icon>
            </div>
          </div>
        </van-uploader>
      </van-cell>
    </van-cell-group>
    <van-cell-group>
      <van-field v-model="remark" placeholder="备注..." icon="edit" type="textarea"></van-field>
    </van-cell-group>

    <van-button round type="danger" size="large" @click="validInfo">提交</van-button>
    <van-popup v-model="showArea" position="bottom">
      <van-area :area-list="areaList" title="选择省市区" @confirm="onAreaConfirm" @cancel="showArea = false" />
    </van-popup>
    <van-popup v-model="showCenter" position="bottom">
      <van-picker showToolbar :columns="centerColumns" title="选择服务中心" @cancel="showCenter = false" @confirm="onCenterConfirm" />
    </van-popup>
    <van-popup v-model="showXiaoqu" position="bottom">
      <van-nav-bar class="nav_bar" title="选择小区" left-text="取消" left-arrow clickable @click-left="showXiaoqu=false" />
      <van-radio-group v-model="xiaoquIndex" style="margin-top: 50px;">
        <van-cell-group>
          <van-cell v-for="(item, i) in suggestXiaoqus" :key="i" :title="item.title" :label="item.address" @click="onXiaoquConfirm(item)">
            <van-radio slot="right-icon" :name="i" />
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>
  </div>
</template>

<script>
import {
  Uploader,
  Picker,
  Area,
  Toast,
  RadioGroup,
  Radio,
  NavBar
} from 'vant';
import { SHOP_REG } from '@/api/user';
import areaList from '../module-address-edit/area.json';
import { UPLOAD_FILE } from '@/api/global';
import { ALL_CENTERS } from '@/api/shop';
import wxConfig from '@/vue/mixin/wx-config';
export default {
  mixins: [wxConfig],
  props: {
    code: [String],
    upname: [String],
    upxiaoqu: [String],
    upcenter: [String, Number]
  },
  data() {
    const user = this.getUser();
    return {
      realname: user.realname,
      mobile: user.mobile,
      lasttel: user.lasttel,
      idCard: user.idCard,
      tProvince: user.tProvince,
      tCity: user.tCity,
      tArea: user.tArea,
      tXiaoqu: user.tXiaoqu,
      tShopname: user.tShopname,
      centreId: this.upcenter || user.centreId,
      lng: 0,
      lat: 0,
      images: [{
        title: '身份证照片(正面)',
        file: null,
      }, {
        title: '身份证照片(反面)',
        file: null,
      }, {
        title: '工商营业执照照片',
        file: null,
      }, {
        title: '食品经营许可证',
        file: null,
      }, {
        title: '门店照片',
        file: null,
      }],
      areaList,
      showArea: false,
      showCenter: false,
      showXiaoqu: false,
      remark: '',
      centers: [],
      centerIndex: -1,
      suggestXiaoqus: [],
      xiaoquIndex: -1
    }
  },

  computed: {
    area() {
      return this.tProvince + ' ' + this.tCity + ' ' + this.tArea;
    },
    centerColumns() {
      let columns = [];
      this.centers.forEach(center => {
        columns.push(center.name);
      });

      return columns;
    },

    xiaoquColumns() {
      let columns = [];
      this.suggestXiaoqus.forEach(xiaoqu => {
        columns.push(xiaoqu.address);
      });

      return columns;
    },

    centerText() {
      return this.centers[this.centerIndex].name;
    },

    imageSelected() {
      return (this.images[0].file && this.images[1].file);
    }
  },
  vuelidation: {
    data: {
      realname: {
        required: true,
        msg(){
        	return "请填写姓名"
				}
      },
      mobile: {
        required: true,
        mobile: true,
        msg(){
        	return "手机号码错误"
				}
      },
      lasttel: {
        required: true,
        mobile: true,
        msg(){
        	return "请填写紧急联系人号码"
				}
      },
      idCard: {
        required: true,
        idcard: true,
        msg(){
        	return "请填写身份证号码"
				}
      },
      tProvince: {
        required: true,
        msg(){
        	return "请选择省市区"
				}
      },
      tCity: {
        required: true,
        msg(){
        	return "请选择省市区"
				}
      },
      tArea: {
        required: true,
        msg(){
        	return "请选择省市区"
				}
      },
      tXiaoqu: {
        required: true,
        betweenLength: {
          min: 2,
          max: 26,
        },
        msg(){
        	return "请输入并选择附近小区"
				}
      },
      tShopname: {
        required: true,
        betweenLength: {
          min: 2,
          max: 32,
        },
        msg(){
        	return "请填写详细地址"
				}
      },
    }
  },
  created() {
    //5.9
    // if (this.user.isteam === 3) { //已经是团长
    //     this.$toast('您已经是团长了，1秒后跳转到首页');
    //     let vm = this;
    //     setTimeout(() => {
    //       vm.$router.push({
    //         name: 'home'
    //       });
    //     }, 1000);
    //     return;
    // }

    this.wxconfig();
    this.onLocation();
    if (this.user.isteamDesc) {
      const desc = JSON.parse(this.user.isteamDesc);
      this.remark = desc.remark;
      desc.images.forEach((image, i) => {
        this.images[i].file = {url: image, content: image};
      })
    }
    this.$reqGet(ALL_CENTERS).then(res => {
      this.centers.push(...res.data.data);

      if (!this.centreId) {
        this.onCenterConfirm('', 0);
      } else {
        for (let i = 0; i < this.centers.length; ++i) {
          if (this.centers[i].centreId == this.centreId) {
            this.onCenterConfirm('', i);
            break;
          }
        }
      }
    });
  },

  methods: {
    afterRead(i) {
      let vm = this;
      return file => {
        vm.images[i].file = file;
        console.log(vm.images[i].file);
        let fd = new FormData();
        fd.append('file', file.file);
        vm.$reqPost(UPLOAD_FILE, fd, {
          dataType: 'json'
        }).then(res => {
          file.url = res.data.key;
        }).catch(res => {
          vm.$dialog.alert({
            title: '警告',
            message: res.data.msg
          });
        });
      }
    },

    validInfo() {
      if (this.user.isteam === 4) { //申请中，审核通过未开通
        this.$toast('您已经提交过申请信息');
        return;
      } else if (this.user.isteam === 3) { //已经是团长
        this.$toast('您已经是团长了，1秒后跳转到首页');
        let vm = this;
        setTimeout(() => {
          vm.$router.push({
            name: 'home'
          });
        }, 1000);
        return;
      }

      if (!this.mixValid()) {
        return;
      }

      if (!this.imageSelected) {
        this.$toast('身份证正反面照片没有上传');
        return;
      }

      this.$dialog.confirm({
        title: '请确认服务中心',
        message: '所选服务中心：' + this.centerText
      }).then(() => {
        this.saveUserInfo();
      }).catch(() => {});
    },

    saveUserInfo() {
      let desc = {
        remark: this.remark,
        images: []
      };

      this.images.forEach(image => {
        desc.images.push(image.file ? image.file.url : '');
      });

      let shop = {
        id: this.user.id,
        realname: this.realname,
        mobile: this.mobile,
        lasttel: this.lasttel,
        idCard: this.idCard,
        tProvince: this.tProvince,
        tCity: this.tCity,
        tArea: this.tArea,
        tXiaoqu: this.tXiaoqu,
        tShopname: this.tShopname,
        isteamDesc: JSON.stringify(desc), //使用团长注册描述字段存取照片了
        invitaCode: this.code,
        lng: this.lng,
        lat: this.lat,
        tZuobiao: this.lat + ',' + this.lng,
        centreId: this.centreId
      };

      this.$reqPost(SHOP_REG, shop).then(res => {
        if (res.data.data > 0) {
          this.$toast.success("提交成功，1秒后转到首页");
          let vm = this;
          setTimeout(() => {
            vm.$router.push({
              name: 'home'
            });
          }, 1000);
        } else {
          this.$toast.fail('提交注册失败');
        }
      })
    },

    onAreaConfirm(datas) {
      this.showArea = false;
      this.tProvince = datas[0].name;
      this.tCity = datas[1].name;
      this.tArea = datas[2].name;
    },
    onCenterConfirm(value, index) {
      if (index < this.centers.length) {
        this.centreId = this.centers[index].centreId;
        this.centerIndex = index;
      }
      this.showCenter = false;
    },

    onLocation() {
      let v = this;
      let wx = this.wx;
      wx.ready(function () {
        //调用相关API
        wx.getLocation({
          type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (data) {
            v.lng = data.longitude;
            v.lat = data.latitude;
            v.initBMap().then(BMap => {
              let points = new BMap.Point(data.longitude, data.latitude);
              var convertor = new BMap.Convertor();
              convertor.translate([points], 1, 5, data => {
                if (data.status === 0) {
                  //后台统一存储百度经纬度
                  v.lng = data.points[0].lng;
                  v.lat = data.points[0].lat;
                  let geoc = new BMap.Geocoder();

                  geoc.getLocation(data.points[0], rs => {
                    v.tProvince = rs.addressComponents.province;
                    v.tCity = rs.addressComponents.city;
                    v.tArea = rs.addressComponents.district;
                    if (rs.surroundingPois.length > 0) {
                      v.tXiaoqu = rs.surroundingPois[0].title;
                    }
                  });
                }
              })
            });
          },
          fail: function (data) {
            v.$toast.fail('定位失败');
          }
        });
      });
    },
    initBMap() {
      //console.log("初始化百度地图脚本...");
      const AK = "WGHV8O3FlG3LbAWy3MjaWxRKId0dQoCS";
      const BMap_URL = "https://api.map.baidu.com/api?v=2.0&ak=" + AK + "&s=1&callback=onBMapCallback";
      return new Promise((resolve, reject) => {
        // 如果已加载直接返回
        if (typeof BMap !== "undefined") {
          resolve(BMap);
          return true;
        }
        // 百度地图异步加载回调处理
        window.onBMapCallback = function () {
          console.log("百度地图脚本初始化成功...");
          resolve(BMap);
        };
        // 插入script脚本
        let scriptNode = document.createElement("script");
        scriptNode.setAttribute("type", "text/javascript");
        scriptNode.setAttribute("src", BMap_URL);
        document.body.appendChild(scriptNode);
      });
    },

    searchLocation() {
      let vm = this;
      Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
      });
      this.initBMap().then(BMap => {
        let ls = new BMap.LocalSearch(this.tCity);
        ls.setSearchCompleteCallback(results => {
          Toast.clear();
          console.log(results);
          if (results.Ar) {
            vm.suggestXiaoqus = results.Ar;
            vm.xiaoquIndex = -1;
            vm.showXiaoqu = true;
          }
        });
        ls.search(this.tXiaoqu);
      });
    },

    onXiaoquInput(e) {
      if (e.keyCode == 13) {
        this.$refs.xiaoquInput.blur();
        this.searchLocation();
      }
    },

    onXiaoquConfirm(value) {
      this.tXiaoqu = value.title;
      this.lng = value.point.lng;
      this.lat = value.point.lat;
      this.showXiaoqu = false;
    }
  },

  components: {
    [Uploader.name]: Uploader,
    [Picker.name]: Picker,
    [Area.name]: Area,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [NavBar.name]: NavBar
  }
}
</script>

<style lang="scss" scoped>
	.user_information{
		.user_image_upload{
			position: relative;
			width: 50px;
			height: 50px;
            border: 1px solid $border-color;
            margin-left: 10px;
			img{
				max-width: 100%;
				max-height: 100%;
			}
			i{
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				font-size: 20px;
				color: $border-color;
			}
		}
		.van-cell-group {
			margin-bottom: 10px;
        }
        .image_text {
            flex: 1;
            text-align: left;
            color: gray;
            font-size: 12px;
        }
  }
.nav_bar {
  position: fixed;
  background-color: $red;
  color: white;
  width: 100%;
}

</style>
